//
//  ThumbnailViewController.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/17.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "ThumbnailViewController.h"

#import "PhotoCollectionViewCell.h"
#import "PhotoTool.h"
#import "PhotoModel.h"
#import "MBProgressHUD.h"
#import "ShowBigImageViewController.h"

@interface ThumbnailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong, nonatomic) NSMutableArray<PHAsset *> *arrayDataSource;
@property (assign, nonatomic) BOOL isLayoutOK;

@property (strong, nonatomic) UIView *bottomView;

@end

@implementation ThumbnailViewController

- (NSMutableArray<PHAsset *> *)arrayDataSource{
    
    if (_arrayDataSource == nil) {
        
        _arrayDataSource = [NSMutableArray array];
        
    }
    return _arrayDataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.btnDone.layer.masksToBounds = YES;
    self.btnDone.layer.cornerRadius = 3.0f;
    
    [self.view addSubview: self.collectionView];
    [self setupSubviews];
    [self setupBottomButotnStatus];
    
    [self getOriginalImageBytes];
    
    [self setupNavigation];
    
    [self getPhotosFromAblum];
   
    
}

- (UICollectionView *)collectionView{
    
    if (_collectionView == nil) {
        
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 44) collectionViewLayout:layout];
        
        layout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 9)/4, ([UIScreen mainScreen].bounds.size.width - 9)/4);
        layout.minimumInteritemSpacing = 1.5;
        layout.minimumLineSpacing = 1.5;
        
        layout.sectionInset = UIEdgeInsetsMake(3, 0, 3, 0);
        
        [self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];
        
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
       
        self.collectionView.backgroundColor = [UIColor whiteColor];
        
    }
    
    return _collectionView;
}


- (void)setupSubviews {
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44)];
    self.bottomView.backgroundColor = [UIColor lightGrayColor];
    self.bottomView.userInteractionEnabled = YES;
    [self.view addSubview:self.bottomView];
    
    self.btnPreView = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnPreView.frame = CGRectMake(12, 7, 45, 30);
    [self.btnPreView setTitle:@"预览" forState:UIControlStateNormal];
    [self.btnPreView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self.btnPreView addTarget:self action:@selector(preButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.btnPreView];
    
    self.btnOriginalPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnOriginalPhoto.frame = CGRectMake(60, 7, 55, 30);
    [self.btnOriginalPhoto setTitle:@"原图" forState:UIControlStateNormal];
    [self.btnOriginalPhoto setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.btnOriginalPhoto setImage:[UIImage imageNamed:@"btn_original_circle"] forState:UIControlStateNormal];
    [self.btnOriginalPhoto setImage:[UIImage imageNamed:@"btn_selected"] forState:UIControlStateSelected];
//    self.btnOriginalPhoto.selected = YES;
    
    [self.btnOriginalPhoto addTarget:self action:@selector(originalButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.btnOriginalPhoto];
    
    self.labPhotosBytes = [[UILabel alloc] initWithFrame:CGRectMake(115, 7, 60, 30)];
    self.labPhotosBytes.textColor = [UIColor blackColor];
    [self.bottomView addSubview:self.labPhotosBytes];
    
    self.btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnDone.frame = CGRectMake(self.view.frame.size.width - 10 - 70, self.btnOriginalPhoto.frame.origin.y, 70, 30);
    [self.btnDone setTitle:@"确定" forState:UIControlStateNormal];
    [self.btnDone setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self.btnDone addTarget:self action:@selector(finishedButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.btnDone];
    
    
    
    
    
}


- (void)setupBottomButotnStatus{
    
    if (self.arraySelectPhotos.count > 0) {
        
        self.btnOriginalPhoto.enabled = YES;
        self.btnPreView.enabled = YES;
        self.btnDone.enabled = YES;
        
        [self.btnDone setTitle:[NSString stringWithFormat:@"确定(%ld)",(unsigned long)self.arraySelectPhotos.count] forState:UIControlStateNormal];
        [self.btnOriginalPhoto setTitleColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0] forState:UIControlStateNormal];
        [self.btnPreView setTitleColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0] forState:UIControlStateNormal];
        [self.btnDone setBackgroundColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0]];
        
        [self.btnDone setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
    } else {
        
        self.btnOriginalPhoto.enabled = NO;
        self.btnPreView.enabled = NO;
        self.btnDone.enabled = NO;
        
        [self.btnDone setTitle:@"确定" forState:UIControlStateDisabled];
        
        [self.btnOriginalPhoto setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateDisabled];
        [self.btnPreView setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateDisabled];
        [self.btnDone setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
        
        self.btnDone.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
        
        
    }
    
    
}

- (void)getOriginalImageBytes{
    
    __weak typeof(self) weakself = self;
    
    if (self.isSelectOriginalPhoto && self.arraySelectPhotos.count > 0) {
        
        [[PhotoTool sharePhotoTool] getPhotoBytesWithArray:self.arraySelectPhotos completion:^(NSString *photosBytes) {
           
            weakself.labPhotosBytes.text = [NSString stringWithFormat:@"(%@)",photosBytes];
            
        }];
        
        self.btnOriginalPhoto.selected = self.isSelectOriginalPhoto;
        
    } else {
        
        self.btnOriginalPhoto.selected = NO;
        self.labPhotosBytes.text = nil;
    }
    
}

- (void)getPhotosFromAblum{
    
    
    [self.arrayDataSource addObjectsFromArray: [[PhotoTool sharePhotoTool] getAssetsInAssetCollection:self.assetCollection ascending:YES]];
    
}

- (void)setupNavigation{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 40, 44);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIImage *leftImage = [UIImage imageNamed:@"navBackBtn@2x"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftImage)];
    
    
}

- (void)rightButton{
    
    if (self.CancelBlock) {
        self.CancelBlock();
    }
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)leftImage{
    
    self.browserController.arraySelectPhotos = self.arraySelectPhotos;
    self.browserController.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.arrayDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifierCell = @"cell";
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierCell forIndexPath:indexPath];
    
    cell.selectButton.selected = NO;
    PHAsset *asset = self.arrayDataSource[indexPath.row];
    cell.imagesVie.contentMode = UIViewContentModeScaleAspectFill;
    cell.imagesVie.clipsToBounds = YES;
    
    CGSize size = cell.frame.size;
    
    size.width *= 3;
    size.height *= 3;
    
    __weak typeof(self) weakself = self;
    
    [[PhotoTool sharePhotoTool] requestImageForAsset:asset size:size resizeMode:PHImageRequestOptionsResizeModeExact completion:^(UIImage *image, NSDictionary *info) {
       
        cell.imagesVie.image = image;
        for (PhotoModel *model in weakself.arraySelectPhotos) {
            
            if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
                cell.selectButton.selected = YES;
                break;
            }
            
        }
        
    }];
    
    cell.selectButton.tag = indexPath.row;
    
    [cell.selectButton addTarget:self action:@selector(touchupButton:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
    
}


- (void)touchupButton:(UIButton *)button{
    
    if (self.arraySelectPhotos.count >= self.maxSelectCount && button.selected == NO) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = [NSString stringWithFormat:@"最多只能选择%ld张图片",(long)self.maxSelectCount];
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    
    PHAsset *asset = self.arrayDataSource[button.tag];
    if (!button.selected) {
        
        CAKeyframeAnimation *animate = [self getButtonStatusChangedAnimation];
        [button.layer addAnimation:animate forKey:nil];
        
        
        if (![[PhotoTool sharePhotoTool] judgeAssetisInLocalAblum:asset]) {
            
            return;
        }
        
        PhotoModel *model = [[PhotoModel alloc] init];
        model.asset = asset;
        model.localIdentifier = asset.localIdentifier;
        
        [self.arraySelectPhotos addObject:model];
        
    } else {
        
        for (PhotoModel *model in self.arraySelectPhotos) {
            
            if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
                
                [self.arraySelectPhotos removeObject:model];
                break;
                
            }
            
        }
        
    }
    
    button.selected = !button.selected;
    
    [self setupBottomButotnStatus];
    [self getOriginalImageBytes];
    
    
    
}

#pragma mark UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [self pushShowBigImageViewWithDataArray:self.arrayDataSource selectIndex:indexPath.row];
}

- (void)pushShowBigImageViewWithDataArray:(NSArray<PHAsset *> *)dataArray selectIndex:(NSInteger)selectIndex{
    
    ShowBigImageViewController *bigImage = [[ShowBigImageViewController alloc] init];
    
    bigImage.assets = dataArray;
    bigImage.selectIndex = selectIndex;
    bigImage.shouldReverseAssets = NO;
    bigImage.maxSelectCount = self.maxSelectCount;
    bigImage.arraySelectPhotos = self.arraySelectPhotos;
    bigImage.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    bigImage.isPresent = NO;
    
    __weak typeof(self) weakself = self;
    [bigImage setOnSelectedPhotos:^(NSArray<PhotoModel *> *selectModle, BOOL isSelectOriginalPhoto) {
        
        weakself.isSelectOriginalPhoto = isSelectOriginalPhoto;
        [weakself.arraySelectPhotos removeAllObjects];
        [weakself.arraySelectPhotos addObjectsFromArray:selectModle];
        
        [weakself.collectionView reloadData];
        [weakself getOriginalImageBytes];
        [weakself setupBottomButotnStatus];
        
    }];
    
    
    
    
    [bigImage setBtnDoneBlock:^(NSArray<PhotoModel *> *photoArray, BOOL isSelectOtiginalPhoto) {
        
        NSLog(@"---%@====photo = %@",weakself.arraySelectPhotos,photoArray);
//        __strong typeof(weakself) strongSelf = weakself;
        weakself.isSelectOriginalPhoto = isSelectOtiginalPhoto;
//        [weakself.arraySelectPhotos removeAllObjects];
//        [weakself.arraySelectPhotos addObjectsFromArray:photoArray];
        NSLog(@"---%@====photo = %@",weakself.arraySelectPhotos,photoArray);
        [weakself finishedButton:nil];
        
    }];
    
    
    
    
    [self.navigationController pushViewController:bigImage animated:YES];
}

- (void)preButtonAction:(UIButton *)button{
    NSLog(@"%s",__func__);
    NSMutableArray<PHAsset *> *assetArray = [NSMutableArray array];
    
    for (PhotoModel *model in self.arraySelectPhotos) {
        
        [assetArray addObject:model.asset];
        
    }
    
    [self pushShowBigImageViewWithDataArray:assetArray selectIndex:assetArray.count - 1];
    
}

- (void)originalButtonAction:(UIButton *)button{
    NSLog(@"%s",__func__);
    self.isSelectOriginalPhoto = !self.btnOriginalPhoto.selected;
    [self getOriginalImageBytes];
    
}

- (void)finishedButton:(UIButton *)button{
    NSLog(@"%s----%@",__func__,self.arraySelectPhotos);
    if (self.DoneBlock) {
        self.DoneBlock(self.arraySelectPhotos,self.isSelectOriginalPhoto);
    }
}

- (CAKeyframeAnimation *)getButtonStatusChangedAnimation{
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    
    animation.duration = 0.3;
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    
    animation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    return animation;
    
}



- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    _isLayoutOK = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
